import React, {useEffect, useState} from "react";
import {useLocation, useNavigate} from "react-router-dom";
import {Layout, Menu} from "antd";
import PubSub from 'pubsub-js'
import {findSideBarRoutes} from "@/routes";
import {XRoutes} from "@/routes/types";
import type {MenuProps} from "antd";

// import "./index.less";

// https://ant.design/components/menu-cn/
type MenuItem = Required<MenuProps>["items"][number];

function getItem(label: React.ReactNode, key: React.Key, icon?: React.ReactNode, children?: MenuItem[], type?: "group"): MenuItem {
    return {
        key,
        icon,
        children,
        label,
        type
    } as MenuItem;
}

const {Sider} = Layout;

interface MenuInfo {
    key: string;
    keyPath: string[];
    item: React.ReactInstance;
    domEvent: React.MouseEvent<HTMLElement> | React.KeyboardEvent<HTMLElement>;
}

function SideBar() {
    // 控制导航栏收缩
    const [collapsed, setCollapsed] = useState(false);
    PubSub.subscribe('siderBar', (_, collapsed) => {
        setCollapsed(collapsed)
    })
    //  展开的菜单
    const [openKeys, setOpenKeys] = useState<string[]>([]);
    //  选中的菜单
    const [selectedKeys, setSelectedKeys] = useState<string[]>([]);
    
    const location = useLocation();
    const navigate = useNavigate();
    
    const {pathname} = location;
    
    useEffect(() => {
        //  当路由发生变化时，设置展开的菜单和选中的菜单
        const openKeys = pathname.split("/").slice(0, 3).join("/");
        setOpenKeys([openKeys]);
        //  当路由发生变化时，设置选中的菜单
        const selectedKeys = pathname.split("/").slice(0).join("/");
        setSelectedKeys([selectedKeys]);
    }, [pathname]);
    
    // 找到要渲染成左侧菜单的路由
    const routes = findSideBarRoutes() as XRoutes
    // 生成菜单 ==> 只有二级菜单
    const menuItems: MenuItem[] = routes.map((route) => {
        return getItem(
            route.meta?.title,
            route.path as string,
            route.meta?.icon,
            route.children?.map((item) => {
                    if (item.index) return null;
                    return getItem(
                        // @ts-ignore
                        item.meta?.title as string,
                        item.path as string
                    );
                }
            )
        )
            ;
    });
    
    const handleMenuClick = ({key}: MenuInfo) => {
        navigate(key);
    };
    
    const handleOpenChange = (openKeys: string[]) => {
        setOpenKeys(openKeys);
    };
    
    return (
        <Sider style={{background: "white", borderRight: "2px solid #eee"}} trigger={null} collapsible
               collapsed={collapsed}>
            <div style={{textAlign: "center", height: 64}}>
                <img style={{
                    width: "100%",
                    height: "100%",
                    objectFit: "contain"
                }} src={"http://localhost:8080/public/uploads/d18986d1c665a0cc8ebdba400.png"}
                     alt={'xh'}/>
            </div>
            {/*菜单栏*/}
            <Menu
                theme="light"
                mode="inline"
                openKeys={openKeys}
                selectedKeys={selectedKeys}
                items={menuItems}
                onClick={handleMenuClick}
                onOpenChange={handleOpenChange}
            ></Menu>
        </Sider>
    )
        ;
}

export default SideBar;
